<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>试卷详情</span>
        <el-button style="float: right; padding: 3px 0" type="text" @click="goBack">返回列表</el-button>
      </div>
      
      <div v-loading="loading">
        <div class="paper-header">
          <h2 class="paper-title">{{ paper.title }}</h2>
          <el-tag :type="paper.status === 0 ? 'info' : 'success'">
            {{ paper.statusName }}
          </el-tag>
        </div>
        
        <el-divider></el-divider>
        
        <div class="paper-info">
          <div class="info-row">
            <div class="info-item">
              <span class="label">学科：</span>
              <span>{{ paper.subjectName }}</span>
            </div>
            <div class="info-item">
              <span class="label">教育阶段：</span>
              <span>{{ paper.educationLevelName }}</span>
            </div>
          </div>
          
          <div class="info-row">
            <div class="info-item">
              <span class="label">考试时长：</span>
              <span>{{ paper.duration }} 分钟</span>
            </div>
            <div class="info-item">
              <span class="label">总分：</span>
              <span>{{ paper.totalScore }} 分</span>
            </div>
          </div>
          
          <div class="info-row">
            <div class="info-item">
              <span class="label">创建人：</span>
              <span>{{ paper.creatorName }}</span>
            </div>
            <div class="info-item">
              <span class="label">创建时间：</span>
              <span>{{ formatDateTime(paper.createTime) }}</span>
            </div>
          </div>
          
          <div class="info-row" v-if="paper.description">
            <div class="info-item full-width">
              <span class="label">试卷说明：</span>
              <div class="description">{{ paper.description }}</div>
            </div>
          </div>
        </div>
        
        <el-divider></el-divider>
        
        <!-- 试卷内容 -->
        <div class="paper-content">
          <div v-for="(section, sectionIndex) in sections" :key="sectionIndex" class="question-section">
            <h3 v-if="section.questions.length > 0" class="section-title">{{ section.name }}</h3>
            
            <div v-for="(question, questionIndex) in section.questions" :key="questionIndex" class="question-item">
              <div class="question-header">
                <div class="question-title">
                  <span class="question-index">{{ sectionIndex + 1 }}-{{ questionIndex + 1 }}.</span>
                  <span v-html="question.content"></span>
                  <span class="question-score">（{{ question.score }}分）</span>
                </div>
              </div>
              
              <!-- 选项（单选题和多选题） -->
              <div v-if="question.questionType === 1 || question.questionType === 2" class="question-options">
                <div v-for="(option, optionIndex) in parseOptions(question.options)" :key="optionIndex" class="option-item">
                  <span class="option-key">{{ option.key }}.</span>
                  <span class="option-content" v-html="option.content"></span>
                </div>
              </div>
              
              <!-- 答案和解析 -->
              <div class="question-answer">
                <div class="answer-label">参考答案：</div>
                <div class="answer-content">
                  <!-- 单选题答案 -->
                  <template v-if="question.questionType === 1">
                    {{ question.answer }}
                  </template>
                  
                  <!-- 多选题答案 -->
                  <template v-else-if="question.questionType === 2">
                    {{ question.answer }}
                  </template>
                  
                  <!-- 判断题答案 -->
                  <template v-else-if="question.questionType === 3">
                    {{ question.answer === 'true' ? '正确' : '错误' }}
                  </template>
                  
                  <!-- 填空题答案 -->
                  <template v-else-if="question.questionType === 4">
                    <div v-for="(blank, blankIndex) in parseBlanks(question.answer)" :key="blankIndex" class="blank-answer">
                      <span class="blank-index">空{{ blankIndex + 1 }}：</span>
                      <span class="blank-text">{{ blank }}</span>
                    </div>
                  </template>
                  
                  <!-- 简答题答案 -->
                  <template v-else-if="question.questionType === 5">
                    <div v-html="question.answer"></div>
                  </template>
                </div>
                
                <!-- 解析 -->
                <div v-if="question.analysis" class="analysis">
                  <div class="answer-label">答案解析：</div>
                  <div class="analysis-content" v-html="question.analysis"></div>
                </div>
              </div>
            </div>
          </div>
        </div>
        
        <div class="action-area">
          <el-button type="primary" @click="handleEdit" v-if="paper.status === 0">编辑试卷</el-button>
          <el-button type="success" @click="handlePublish" v-if="paper.status === 0">发布试卷</el-button>
          <el-button type="danger" @click="handleDelete" v-if="paper.status === 0">删除试卷</el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import { getPaperDetail, deletePaper, publishPaper } from '@/api/paper';

export default {
  name: 'PaperDetail',
  data() {
    return {
      loading: false,
      paper: {
        id: null,
        title: '',
        description: '',
        totalScore: 0,
        duration: 0,
        subjectId: null,
        subjectName: '',
        educationLevel: null,
        educationLevelName: '',
        status: 0,
        statusName: '',
        creatorId: null,
        creatorName: '',
        createTime: null,
        updateTime: null,
        questions: []
      },
      sections: [
        { type: 1, name: '一、单选题', questions: [] },
        { type: 2, name: '二、多选题', questions: [] },
        { type: 3, name: '三、判断题', questions: [] },
        { type: 4, name: '四、填空题', questions: [] },
        { type: 5, name: '五、简答题', questions: [] }
      ]
    };
  },
  created() {
    this.getPaperDetail();
  },
  methods: {
    // 获取试卷详情
    getPaperDetail() {
      this.loading = true;
      const paperId = this.$route.params.id;
      if (!paperId) {
        this.$message.error('试卷ID不能为空');
        this.$router.push('/papers');
        return;
      }
      
      getPaperDetail(paperId).then(response => {
        this.paper = response.data;
        
        // 按题型分组
        this.sections.forEach(section => {
          section.questions = [];
        });
        
        if (this.paper.questions && this.paper.questions.length > 0) {
          this.paper.questions.forEach(question => {
            const section = this.sections.find(s => s.type === question.questionType);
            if (section) {
              section.questions.push(question);
            }
          });
        }
        
        this.loading = false;
      }).catch(() => {
        this.loading = false;
        this.$message.error('获取试卷详情失败');
        this.$router.push('/papers');
      });
    },
    // 编辑试卷
    handleEdit() {
      this.$router.push(`/paper/edit/${this.paper.id}`);
    },
    // 发布试卷
    handlePublish() {
      this.$confirm('确定要发布该试卷吗? 发布后将不能修改', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        publishPaper(this.paper.id).then(() => {
          this.$message.success('发布成功');
          this.getPaperDetail();
        }).catch(() => {
          this.$message.error('发布失败');
        });
      }).catch(() => {});
    },
    // 删除试卷
    handleDelete() {
      this.$confirm('确定要删除该试卷吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deletePaper(this.paper.id).then(() => {
          this.$message.success('删除成功');
          this.$router.push('/papers');
        }).catch(() => {
          this.$message.error('删除失败');
        });
      }).catch(() => {});
    },
    // 返回列表
    goBack() {
      this.$router.push('/papers');
    },
    // 格式化日期时间
    formatDateTime(dateTime) {
      if (!dateTime) return '';
      const date = new Date(dateTime);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    // 解析选项
    parseOptions(optionsStr) {
      if (!optionsStr) return [];
      
      try {
        return JSON.parse(optionsStr);
      } catch (e) {
        console.error('解析选项失败', e);
        return [];
      }
    },
    // 解析填空题答案
    parseBlanks(answerStr) {
      if (!answerStr) return [];
      
      try {
        return JSON.parse(answerStr);
      } catch (e) {
        return [answerStr];
      }
    }
  }
};
</script>

<style scoped>
.paper-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
}

.paper-title {
  margin: 0;
  font-size: 22px;
  color: #303133;
}

.paper-info {
  margin: 20px 0;
}

.info-row {
  display: flex;
  margin-bottom: 15px;
}

.info-item {
  flex: 1;
  display: flex;
}

.full-width {
  flex-basis: 100%;
}

.label {
  font-weight: bold;
  color: #606266;
  margin-right: 10px;
  min-width: 80px;
}

.description {
  white-space: pre-line;
  color: #606266;
  line-height: 1.6;
}

.paper-content {
  margin: 20px 0;
}

.question-section {
  margin-bottom: 30px;
}

.section-title {
  font-size: 18px;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.question-item {
  margin-bottom: 25px;
  padding: 15px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.question-header {
  margin-bottom: 15px;
}

.question-title {
  line-height: 1.6;
}

.question-index {
  font-weight: bold;
  margin-right: 5px;
}

.question-score {
  font-size: 14px;
  color: #409EFF;
  margin-left: 10px;
}

.question-options {
  margin-left: 20px;
  margin-bottom: 15px;
}

.option-item {
  margin-bottom: 10px;
  display: flex;
}

.option-key {
  font-weight: bold;
  margin-right: 10px;
  min-width: 20px;
}

.question-answer {
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px dashed #ebeef5;
}

.answer-label {
  font-weight: bold;
  color: #409EFF;
  margin-bottom: 10px;
}

.answer-content {
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  line-height: 1.6;
}

.blank-answer {
  margin-bottom: 10px;
}

.blank-index {
  font-weight: bold;
  margin-right: 10px;
}

.analysis {
  margin-top: 15px;
}

.analysis-content {
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  line-height: 1.6;
}

.action-area {
  margin-top: 30px;
  text-align: center;
}
</style> 